<template>
	<el-dialog :title="titleMap" v-model="visible" :width="1048" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" ref="dialogForm" label-width="69px" label-position="right"
			class="el-tabs--border-card" style="border: 1px solid #dedfe0">
			<el-row>
				<el-col :span="13">
					<el-row>
						<el-col :span="6">
							<el-form-item label="色号" prop="color.code">
								<el-input v-model="form.color.code" disabled />
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item label="色名">
								<el-input v-model="form.color.name" disabled />
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item label="订单">
								<el-input v-model="form.quantity" disabled />
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item label="库位" prop="location_name">
								<el-input v-model="form.location_name" disabled />
							</el-form-item>
						</el-col>
					</el-row>
				</el-col>
				<el-col :span="11">
					<el-row>
						<el-col :span="8">
							<el-form-item label="脱水时长" prop="tstime">
								<skDicSelect v-model="form.tstime" :code="'TsTime'" :placeholder="'请选择脱水时长'">
								</skDicSelect>
							</el-form-item>
						</el-col>

						<el-col :span="7">
							<el-form-item label="批号" prop="lot_name">
								<el-input v-model="form.lot_name" @click="openStorage" />
							</el-form-item>
						</el-col>
						<el-col :span="9">
							<el-form-item label="排单日期" prop="potdate">
								<el-date-picker v-model="form.potdate" type="date" value-format="YYYY-MM-DD"
									:placeholder="'请选择日期'" style="width: 100%;"></el-date-picker>
							</el-form-item>
						</el-col>

					</el-row>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="13" style="border-right: 1px solid #dedfe0">
					<sc-VxeTable :tablecode="'pro_pot_rev_list'" :data="form.raw" :gridOps="gridOps"
						:gridEvts="gridEvent" ref="subbe" :sortable="true">
					</sc-VxeTable>
				</el-col>
				<el-col :span="11">
					<el-row>
						<el-col :span="12">
							<el-form-item label="染缸" prop="loom_id">
								<skAutoChoose v-model="form.loom.name" :name="'loom'" @select="loomSelect"
									:params="getQuantity" :assign="form" :sort="'dosage'">
								</skAutoChoose>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="浴比" prop="ratio">
								<el-input v-model="form.ratio" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="浴量">
								<el-input v-model="form.bath_qty" disabled />
							</el-form-item>
						</el-col>

						<el-col :span="12">
							<el-form-item label="配方" prop="revision_id">
								<el-button-group>
									<el-button type="primary" icon="ElIconSearch" @click="openBomPot"
										auto-insert-space>选大货</el-button>
									<el-button type="danger" icon="ElIconSearch" @click="openBomColor"
										auto-insert-space>选小样</el-button>
								</el-button-group>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="工艺" prop="rscode">
								<skAutoChoose v-model="form.dyecraft.name" :name="'dyecraft'"
									@select="(data) => (form.dyecraft = data)" :asKey="'rscode'" :asField="'code'"
									:assign="form" :prepend_width="'60px'" :params="getRsParams">
									<template #prepend>{{
		form.dyecraft.code
	}}</template>
								</skAutoChoose>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="工艺">
								<el-input v-model="form.dyecraft.data" type="textarea" disabled :rows="5"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="后处理" prop="rscodeend">
								<skAutoChoose v-model="form.dyeendcraft.name" :name="'dyeendcraft'" @select="(data) => (form.dyeendcraft = data)
		" :asKey="'rscodeend'" :asField="'code'" :params="getRsEndParams" :assign="form" :prepend_width="'60px'">

									<template #prepend>{{
		form.dyeendcraft.code
	}}</template>
								</skAutoChoose>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="生产要求" prop="dgremark">
								<el-input v-model="form.dgremark" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="投料比" prop="feeding_ratio">
								<el-input v-model="form.feeding_ratio" disabled />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="投料" prop="yarn_quantity">
								<el-input v-model="form.yarn_quantity" disabled />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="投料包" prop="packet_quantity">
								<el-input v-model="form.packet_quantity" disabled />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="投料绞" prop="hank_quantity">
								<el-input v-model="form.hank_quantity" disabled />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="客户要求" prop="remark">
								<el-input v-model="form.remark" type="textarea" maxlength="120" show-word-limit
									disabled />
							</el-form-item>
						</el-col>
					</el-row>
				</el-col>
			</el-row>
		</el-form>

		<template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
	<skBrowserChoose v-model="dialog.storage" :name="'storage_browser'" @close="dialog.storage = false"
		@select="selectStorage" :params="{ material_id: form.material_id }">
	</skBrowserChoose>
	<colorbrowser v-model="dialog.color" @close="dialog.color = false" @select="selectColor"
		:params="{ main_id: form.color_id }">
	</colorbrowser>
	<potbrowser v-model="dialog.pot" @close="dialog.pot = false" @select="selectPotColor"
		:params="{ color_id: form.color_id }">
	</potbrowser>
</template>

<script>
import tool from "@/utils/tool";
import skDicSelect from "@/components/skDicSelect";
import skAutoChoose from "@/components/skAutoChoose";
import skAutoComplete from "@/components/skAutoComplete";

import skBrowserChoose from "@/components/skBrowserChoose";
import colorbrowser from "@/views/pro/color/browser";
import potbrowser from "@/views/pro/pot/browser";
import XEUtils from "xe-utils";

export default {
	emits: ["success", "closed"],
	components: {
		skAutoChoose,
		skAutoComplete,
		skDicSelect,
		skBrowserChoose,
		colorbrowser,
		potbrowser,
	},
	data() {
		return {
			mode: "add",
			dialog: {
				storage: false,
				pot: false,
				color: false,
			},
			gridOps: {
				columns: [
					{
						field: "material.name",
						event: {
							select: ({ e, row }) => {
								row["material"] = e;
								row["procedure"] = e.procedure;
								row["uunit"] = e.uunit ?? {};
								row["ounit"] = e.ounit ?? {};
								row["uunit_id"] = e.uunit_id;
								row["ounit_id"] = e.ounit_id;
								this.calcAuxiliaryQuantity(row);
								this.calcAuxiliaryAmount(row);
							},
						},
					},
					{
						field: "rate",
						event: {
							keyup: ({ row }) => {
								this.calcAuxiliaryQuantity(row);
								this.calcAuxiliaryAmount(row);
							},
						},
					},
					{
						field: "quantity",
						event: {
							keyup: ({ row }) => {
								this.calcAuxiliaryRate(row);
								this.calcAuxiliaryAmount(row);
							},
						},
					},
				],
			},
			gridEvent: {},
			titleMap: "",

			form: {
				place: {},
				color: { name: "" },
				potdate: tool.SYS_DATE(),
				loom: { name: "" },
				dyeendcraft: {},
				raw: [],
				dyecraft: [],
				plan_ids: [],
				revision_id: "",
			},
			rules: {
				// 'main.ColorShade_id': { required: true, message: "请选择颜色深浅" },
				tstime: { required: true, message: "脱水时长必选" },
				lot_name: { required: true, message: "必须选择库存" },
				loom_id: { required: true, message: "必须选择染缸" },
				ratio: { required: true, message: "浴比必填" },
				rscode: { required: true, message: "必须选择工艺" },
				revision_id: { required: true, message: "必须选择配方" },
				potdate: { required: true, message: "排单日期必选" },
			},
			visible: false,
			isSaveing: false,
		};
	},
	mounted() { },
	watch: {
		"form.ratio"(val) {
			this.form.bath_qty = val * this.form.dosage;
			this.resetComputAuxiliary();
		},
	},
	methods: {
		getRsEndParams() {
			return {
				category_id: 2,
				materialid: this.form.material_id,
				parent_code: this.form.rscode,
			};
		},
		getRsParams() {
			let material_id = this.form.material_id;
			let loom_id = this.form.loom_id;
			let rawids = [];
			this.form.raw?.filter((raw) => {
				let spec = raw.material.spec.substr(0, 1);
				if (
					["1", "2", "3", "4"].indexOf(spec) > -1 &&
					rawids.indexOf(spec) == -1
				)
					rawids.push(spec);
			});
			return {
				materialid: material_id,
				loomid: loom_id,
				rawids: rawids,
			};
		},
		openStorage() {
			this.dialog.storage = true;
		},
		openBomPot() {
			this.dialog.pot = true;
		},
		openBomColor() {
			this.dialog.color = true;
		},
		getQuantity() {
			return [
				{
					yarn_quantity: this.form.quantity * this.form.feeding_ratio / 1000,
					material_id: this.form.material_id
				},
			];
		},
		open(mode = "add") {
			this.mode = mode;
			this.visible = true;
			return this;
		},
		//选择小样
		selectColor(data, items) {
			this.dialog.color = false;
			this.form.color_id = data.main.id;
			this.form.color = data.main;
			this.form.raw = items.map((item) => {
				if (item.material) {
					this.calcAuxiliaryQuantity(item);
					this.calcAuxiliaryAmount(item);
					return item;
				} else {
					this.$message.error("配方的某项未找到匹配物料！");
					return false;
				}
			});
			this.form.rscode = data.rscode;
			this.form.dyecraft = data.dyecraft ?? {};
			this.form.dyeendcraft = {};
			this.form.revision_id = data.id;
			this.resetComputAuxiliary();
		},
		//选择小样
		selectPotColor(data, items) {
			this.dialog.pot = false;
			this.form.color_id = data.color.id;
			this.form.color = data.color;
			this.form.raw = items.map((item) => {
				this.calcAuxiliaryQuantity(item);
				this.calcAuxiliaryAmount(item);
				return item;
			});
			this.form.rscode = data.rscode;
			this.form.rscodeend = data.rscodeend;
			this.form.dyecraft = data.dyecraft ?? {};
			this.form.dyeendcraft = data.dyeendcraft ?? {};

			this.form.revision_id = data.revision_id;
		},
		//重新计算助剂用量，金额
		resetComputAuxiliary() {
			this.form.raw = this.form.raw.map((item) => {
				return this.calcAuxiliaryAmount(
					this.calcAuxiliaryQuantity(item)
				);
			});
		},
		//计算金额
		calcAuxiliaryAmount(item) {
			if (item === false) {
				return item;
			}
			item.cost = parseFloat(
				XEUtils.toFixed(
					(item.material.average_price * item.quantity) /
					(1999 - item.uunit_id * 999),
					2
				)
			);
			return item;
		},
		//计算比例
		calcAuxiliaryRate(item) {
			if (item === false) {
				return item;
			}
			// uunit_ 1g 2kg
			let quantity = item.quantity;
			if (item.uunit_id == 1) {
				quantity = item.quantity / 1000;
			}

			if (item.ounit_id == 1) {
				//%*数量/100   =>KG
				item.rate = (quantity * 100) / this.form.yarn_quantity;
			} else {
				//g/L*数量/1000  =>KG
				item.rate = (quantity * 1000) / this.form.bath_qty;
			}
			return item;
		},
		//计算数量
		calcAuxiliaryQuantity(item) {
			if (item === false) {
				return item;
			}
			delete item.id;
			delete item.quantity;
			delete item.new_rate;
			if (item.ounit_id == 1) {
				//%*数量/100   =>KG
				item.quantity = (this.form.yarn_quantity * item.rate) / 100;
			} else {
				//g/L*数量/1000  =>KG
				item.quantity = (this.form.bath_qty * item.rate) / 1000;
			}

			// uunit_ 1g 2kg
			//根据用量设置单位
			if (item.quantity < 1) {
				item.uunit_id = 1;
				item.uunit.name = "g";
				item.quantity = item.quantity * 1000;
			} else {
				item.uunit_id = 2;
				item.uunit.name = "kg";
			}
			item.quantity = parseFloat(XEUtils.toFixed(item.quantity, 6));

			return item;
		},
		//选择库存
		selectStorage(selectdata) {
			let data = selectdata[0];
			this.dialog.storage = false;
			this.form.storage_id = data.id;
			this.form.location_name = data.location.name;
			this.form.lot_name = data.lot.name;
		},
		//表单提交方法
		submit() {
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					var res = await this.$API.pro.pot.saveDyePlan.post(this.form);
					this.isSaveing = false;
					if (res.code == 200) {
						this.$emit("success", this.form, this.mode);
						this.visible = false;
						this.$message.success("开卡成功");
					}
				}
			});
		},
		// async getItems(id) {
		//   console.log(id);
		// },
		loomSelect(data) {
			this.form.ratio = data.ratio;
			this.form.dosage = data.dosage;
			this.resetComputAuxiliary();
		},
		//表单注入数据
		setData(data, details) {
			this.form = Object.assign(this.form, tool.removeNull(data));
			this.form.plan_ids = details.map((v) => v.id);

			this.form.merge_count = details.length;
			this.titleMap =
				this.form.company_name + "(" + this.form.material.name + ")";
			// this.getItems(data.id);
		},
	},
};
</script>

<style>
.attachments .el-upload--picture-card,
.attachments .el-upload-list--picture-card .el-upload-list__item {
	width: 100px;
	height: 100px;
	overflow: hidden;
}
</style>
